#include "dao.h"

void scan_admin(FILE* fp, int index) {
    fscanf(fp, "%s %s %hd", admin[index].account, admin[index].passwd, &admin[index].birth);
}

void scan_student(FILE* fp, int index) {
    fscanf(fp, "%s %c %s %s %hd %hd %hd %hd %hd %hd", student[index].name, &student[index].sex, student[index].id, student[index].passwd, &student[index].chinese, &student[index].english, &student[index].math, &student[index].time, &student[index].birth, &student[index].exist);
}

void scan_teacher(FILE* fp, int index) {
    fscanf(fp, "%s %c %s %s %hd %hd %hd", teacher[index].name, &teacher[index].sex, teacher[index].id,teacher[index].passwd, &teacher[index].time, &teacher[index].birth, &teacher[index].exist);
}

// 数组、结构体等数据保存到文件中
void get_data(const char* file, size_t length, scan_buffer scan)
{
    FILE *fp = fopen(file, "r");
    if (fp == NULL) {
        goto _end;
    }

    // 按行读取文件
    // while (!feof(fp))
    // {
    //     fgets(buffer, length, fp);
    // }

    for(int i = 0; i < length; i++) {
        scan(fp, i);
    }

_end:
    fclose(fp);
}

void print_admin(FILE* fp, int index) {
    fprintf(fp, "%s %s %hd", admin[index].account, admin[index].passwd, &admin[index].birth);
}

void print_student(FILE* fp, int index) {
    fprintf(fp, "%s %c %s %s %hd %hd %hd %hd %hd %hd", student[index].name, &student[index].sex, student[index].id, student[index].passwd, &student[index].chinese, &student[index].english, &student[index].math, &student[index].time, &student[index].birth, &student[index].exist);
}

void print_teacher(FILE* fp, int index) {
    fprintf(fp, "%s %c %s %s %hd %hd %hd", teacher[index].name, &teacher[index].sex, teacher[index].id,teacher[index].passwd, &teacher[index].time, &teacher[index].birth, &teacher[index].exist);
}

void set_data(const char* file, size_t length, scan_buffer print) {
    FILE *fp = fopen(file, "w");
    if (fp == NULL) {
        goto _end;
    }

    for(int i = 0; i < length; i++) {
        print(fp, i);
    }

_end:
    fclose(fp);
}

void load_data()
{
    admin = calloc(MAX_ADMIN, ADMIN_SIZE);
    student = calloc(MAX_STUDENT, STUDENT_SIZE);
    teacher = calloc(MAX_TEACHER, TEACHER_SIZE);

    get_data(ADMIN_FILE, ADMIN_SIZE, scan_admin);
    get_data(STUDENT_FILE, STUDENT_SIZE, scan_student);
    get_data(TEACHER_FILE, TEACHER_SIZE, scan_teacher);
}

void save_data() {
    set_data(ADMIN_FILE, ADMIN_SIZE, print_admin);
    set_data(STUDENT_FILE, STUDENT_SIZE, print_student);
    set_data(TEACHER_FILE, TEACHER_SIZE, print_teacher);

    free(admin);
    free(student);
    free(teacher);
}